package org.example.net;

import lombok.SneakyThrows;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * @Auther:Liu
 * @Testname:DemoC1
 * @Date:2025/8/27 17:29
 */
public class DemoC1  {
    @SneakyThrows
    public static void main(String[] args) {
        System.out.println("开启通讯");
        //服务端 指定端口
        ServerSocket serverSocket = new ServerSocket(8890);
        System.out.println("开启了服务"+serverSocket);
        //开启一个通讯
        Socket socket = serverSocket.accept();
        //发送内容
       new Thread(() -> {
           try {
               OutputStream outputStream = socket.getOutputStream();
               Scanner scanner = new Scanner(System.in);
               while(true){
                   System.out.println("Input:");
                   String message = scanner.nextLine();
                   outputStream.write(message.getBytes(StandardCharsets.UTF_8));
                   if ("bye".equals(message)) {
                       break;
                   }
               }
           } catch (IOException e) {
               throw new RuntimeException(e);
           }
       }).start();

       new Thread(() -> {
           try {
               InputStream inputStream = socket.getInputStream();
               byte[] bytes = new byte[1024];
               while (true){
                   int len = inputStream.read(bytes);
                   String s = new String(bytes, 0, len, StandardCharsets.UTF_8);
                   System.out.println(s);
                   if ("bye".equals(s)) {
                       break;
                   }
               }
           } catch (IOException e) {
               throw new RuntimeException(e);
           }
       }).start();
    }
}
